﻿using System;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace referrals.Layouts.referrals
{
    public partial class NewReferralsRiskAssessment : LayoutsPageBase
    {
        private const string SortDirection = "DateReferred DESC";
        protected const string StrClient = "SELECT Clients.NHSNumber, Clients.Title, Clients.FirstName, Clients.MiddleName, Clients.LastName, Clients.DOB, Clients.Gender, Clients.Area, Clients.Location, Contacts.ReasonReferred, Contacts.DateReferred, Contacts.ReferredBy, Contacts.Description, Contacts.Type, Contacts.ContactBy1, Contacts.Date, Contacts.Urgency, Contacts.ContactBy2, Contacts.AssessmentDate, Contacts.ReportFeedback, Contacts.ReportSent, Contacts.referralResponse, Contacts.DNW, Contacts.RefOutcome, Contacts.Closed, Clients.UID, [DOB], Contacts.RefDiscussion, Contacts.FOutcome, Contacts.PapersLocation FROM Clients LEFT JOIN Contacts ON Clients.UID = Contacts.ClientID WHERE (((Contacts.ReasonReferred)=1 Or (Contacts.ReasonReferred)=2 Or (Contacts.ReasonReferred)=3) AND ((Contacts.Type)=62) AND ((Contacts.Closed)=0));";
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(Connection.GetConnStrSql()))
            {
                //SqlConnection conn = connection.GetConnection();
                SqlCommand sqlCommand = new SqlCommand(StrClient, conn);
                conn.Open();

                SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
                DataSet ds = new DataSet();
                da.Fill(ds);

                //grdReferralDetails.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);

                using (ds)
                {
                    grdDetails.DataSource = ds;
                    grdDetails.DataBind();
                }

                ViewState["SortExpr"] = SortDirection;
                DataView dvContacts = Getdata();
                grdDetails.DataSource = dvContacts;
                grdDetails.DataBind();
            }
        }

        protected string GetAge(DateTime birthday)
        {
            int years = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year - 1;
            return String.Format("Age: {0} Year(s)", years);
        }

        protected void grdDetails_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblGender = (e.Row.FindControl("lblGender") as Label);
                Table tblHeader = (e.Row.FindControl("tblHeader") as Table);
                if (lblGender != null)
                {
                    if (lblGender.Text == "Female")
                    {
                        if (tblHeader != null)
                        {
                            tblHeader.BackColor = System.Drawing.Color.PaleVioletRed;
                            tblHeader.ForeColor = System.Drawing.Color.White;
                        }
                    }
                    else
                    {
                        if (tblHeader != null)
                        {
                            tblHeader.BackColor = System.Drawing.Color.Blue;
                            tblHeader.ForeColor = System.Drawing.Color.White;
                        }
                    }
                }

                //************ begin Referred By DropDownList *********
                DropDownList ddlReferredBy = (e.Row.FindControl("ddlReferredBy") as DropDownList);
                if (ddlReferredBy != null)
                {

                    ddlReferredBy.DataSource = GetData("SELECT * FROM referral order by Organisation asc;");
                    ddlReferredBy.DataTextField = "Organisation";
                    ddlReferredBy.DataValueField = "RefID";
                    ddlReferredBy.DataBind();

                    //Add Default Item in the DropDownList
                    ddlReferredBy.Items.Insert(0, new ListItem("Please select"));

                    var label = e.Row.FindControl("lblReferredBy") as Label;
                    if (label != null)
                    {
                        string referredBy = label.Text;
                        if (referredBy != null && referredBy.Length >= 1)
                        {
                            if (ddlReferredBy.Items.FindByValue(referredBy) != null)
                            {
                                ddlReferredBy.Items.FindByValue(referredBy).Selected = true;
                            }
                        }
                    }
                }

                //This is for the Referral reason dropdown
                DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
                if (ddlReasons != null)
                {
                    ddlReasons.DataSource = GetData("select * from Picklists where type = 'Reason' order by Description asc;");
                    ddlReasons.DataTextField = "Description";
                    ddlReasons.DataValueField = "Code";
                    ddlReasons.DataBind();

                    //Add Default Item in the DropDownList
                    ddlReasons.Items.Insert(0, new ListItem("Please select"));

                    //Select the Country of Customer in DropDownList
                    var label2 = e.Row.FindControl("lblReasons") as Label;
                    if (label2 != null)
                    {
                        string referralReason = label2.Text;
                        if (referralReason != null && referralReason.Length >= 1)
                        {
                            if (ddlReasons.Items.FindByValue(referralReason) != null)
                            {
                                ddlReasons.Items.FindByValue(referralReason).Selected = true;
                            }
                        }
                    }
                }

                //************ begin Initial Outcome By DropDownList *********
                DropDownList ddlInitialOutcome = (e.Row.FindControl("ddlInitialOutcome") as DropDownList);
                if (ddlInitialOutcome != null)
                {

                    ddlInitialOutcome.DataSource = GetData("SELECT Picklists.Code, Picklists.Description, Picklists.Type FROM Picklists WHERE (((Picklists.Type)='outcome')) ORDER BY Picklists.Description;");
                    ddlInitialOutcome.DataTextField = "Description";
                    ddlInitialOutcome.DataValueField = "Code";
                    ddlInitialOutcome.DataBind();

                    //Add Default Item in the DropDownList
                    ddlInitialOutcome.Items.Insert(0, new ListItem("Please select"));

                    var label = e.Row.FindControl("lblInitialOutcome") as Label;
                    if (label != null)
                    {
                        string initialoutcome = label.Text;
                        if (initialoutcome != null && initialoutcome.Length >= 1)
                        {
                            if (ddlInitialOutcome.Items.FindByValue(initialoutcome) != null)
                            {
                                ddlInitialOutcome.Items.FindByValue(initialoutcome).Selected = true;
                            }
                        }
                    }
                }

                //************ begin Current Location DropDownList *********
                DropDownList ddlCurrentLocation = (e.Row.FindControl("ddlCurrentLocation") as DropDownList);
                if (ddlCurrentLocation != null)
                {

                    ddlCurrentLocation.DataSource = GetData("SELECT Picklists.Code, Picklists.Description, Picklists.Type FROM Picklists WHERE (((Picklists.Type)='Location')) ORDER BY Picklists.Description;");
                    ddlCurrentLocation.DataTextField = "Description";
                    ddlCurrentLocation.DataValueField = "Code";
                    ddlCurrentLocation.DataBind();

                    //Add Default Item in the DropDownList
                    ddlCurrentLocation.Items.Insert(0, new ListItem("Please select"));

                    var label = e.Row.FindControl("lblCurrentLocation") as Label;
                    if (label != null)
                    {
                        string currentLocation = label.Text;
                        if (currentLocation != null && currentLocation.Length >= 1)
                        {
                            if (ddlCurrentLocation.Items.FindByValue(currentLocation) != null)
                            {
                                ddlCurrentLocation.Items.FindByValue(currentLocation).Selected = true;
                            }
                        }
                    }
                }

                // ******************** Begin Allocated to Dropdown 1
                DropDownList ddlContactBy1 = (e.Row.FindControl("ddlContactBy1") as DropDownList);
                if (ddlContactBy1 != null)
                {
                    ddlContactBy1.DataSource = GetData("SELECT * from staff;");
                    ddlContactBy1.DataTextField = "Name";
                    ddlContactBy1.DataValueField = "StaffId";
                    ddlContactBy1.DataBind();

                    //Add Default Item in the DropDownList
                    ddlContactBy1.Items.Insert(0, new ListItem("Please select"));

                    var label = e.Row.FindControl("lblContactBy1") as Label;
                    if (label != null)
                    {
                        string contactby1 = label.Text;
                        if (contactby1 != null && contactby1.Length >= 1)
                        {
                            if (ddlContactBy1.Items.FindByValue(contactby1) != null)
                            {
                                ddlContactBy1.Items.FindByValue(contactby1).Selected = true;
                            }
                        }
                    }
                }

                // ******************** Begin Allocated to Dropdown 2
                DropDownList ddlContactBy2 = (e.Row.FindControl("ddlContactBy2") as DropDownList);
                if (ddlContactBy2 != null)
                {
                    ddlContactBy2.DataSource = GetData("SELECT * from staff;");
                    ddlContactBy2.DataTextField = "Name";
                    ddlContactBy2.DataValueField = "StaffId";
                    ddlContactBy2.DataBind();

                    //Add Default Item in the DropDownList
                    ddlContactBy2.Items.Insert(0, new ListItem("Please select"));

                    var label = e.Row.FindControl("lblContactBy2") as Label;
                    if (label != null)
                    {
                        string contactby2 = label.Text;
                        if (contactby2 != null && contactby2.Length >= 1)
                        {
                            if (ddlContactBy2.Items.FindByValue(contactby2) != null)
                            {
                                ddlContactBy2.Items.FindByValue(contactby2).Selected = true;
                            }
                        }
                    }
                }

                //******** Begin Urgency DropdowlList **************
                DropDownList ddlUrgency = (e.Row.FindControl("ddlUrgency") as DropDownList);
                if (ddlUrgency != null)
                {

                    List<ListItem> items = new List<ListItem>
                        {
                            new ListItem("Emergency", "Emergency"),
                            new ListItem("Routine", "Routine"),
                            new ListItem("Urgent", "Urgent")
                        };
                    items.Sort((item1, item2) => String.Compare(item1.Text, item2.Text, StringComparison.Ordinal));
                    ddlUrgency.Items.AddRange(items.ToArray());

                    var label = e.Row.FindControl("lblUrgency") as Label;
                    if (label != null)
                    {
                        string urgency = label.Text;
                        ddlUrgency.Items.FindByValue(urgency).Selected = true;
                    }
                }

                //This is for the Referrals Type dropdown
                //***************************************
                //Find the DropDownList in the Row
                DropDownList ddlCpaStage = (e.Row.FindControl("ddlCpaStage") as DropDownList);
                if (ddlCpaStage != null)
                {
                    ddlCpaStage.DataSource = GetData("SELECT Picklists.Code, Picklists.Description, Picklists.Type FROM Picklists WHERE (((Picklists.Type)='stage')) OR (((Picklists.Code)=167 Or (Picklists.Code)=168));");
                    ddlCpaStage.DataTextField = "Description";
                    ddlCpaStage.DataValueField = "Code";
                    ddlCpaStage.DataBind();

                    //Add Default Item in the DropDownList
                    ddlCpaStage.Items.Insert(0, new ListItem("Please select"));
                }

                //Select the type of referral in DropDownList
                var label1 = e.Row.FindControl("lblCpaStage") as Label;
                if (label1 != null)
                {
                    string type = label1.Text;
                    if (ddlCpaStage != null) ddlCpaStage.Items.FindByValue(type).Selected = true;
                }
                //****************************************************

                //************ begin Final Outcome By DropDownList *********
                DropDownList ddlFinalOutcome = (e.Row.FindControl("ddlFinalOutcome") as DropDownList);
                if (ddlFinalOutcome != null)
                {
                    ddlFinalOutcome.DataSource = GetData("SELECT Picklists.Code, Picklists.Description, Picklists.Type FROM Picklists WHERE (((Picklists.Type)='Foutcome')) ORDER BY Picklists.Description;");
                    ddlFinalOutcome.DataTextField = "Description";
                    ddlFinalOutcome.DataValueField = "Code";
                    ddlFinalOutcome.DataBind();

                    //Add Default Item in the DropDownList
                    ddlFinalOutcome.Items.Insert(0, new ListItem("Please select"));

                    var label = e.Row.FindControl("lblFinalOutcome") as Label;
                    if (label != null)
                    {
                        string finaloutcome = label.Text;
                        if (finaloutcome != null && finaloutcome.Length >= 1)
                        {
                            if (ddlFinalOutcome.Items.FindByValue(finaloutcome) != null)
                            {
                                ddlFinalOutcome.Items.FindByValue(finaloutcome).Selected = true;
                            }
                        }
                    }
                }

                TextBox txtDateReferred = (e.Row.FindControl("txtDateReferred") as TextBox);
                if (txtDateReferred != null)
                {

                    var label = (e.Row.FindControl("lblDateReferred") as Label);
                    if (label != null && label.Text.Length >= 1)
                    {
                        txtDateReferred.Text = Convert.ToDateTime(label.Text).ToString("dd/MM/yyyy");
                    }
                }

                TextBox txtDateReviewed = (e.Row.FindControl("txtDateReviewed") as TextBox);
                if (txtDateReferred != null)
                {

                    var label = (e.Row.FindControl("lblDateReviewed") as Label);
                    if (label != null && label.Text.Length >= 1)
                    {
                        txtDateReviewed.Text = Convert.ToDateTime(label.Text).ToString("dd/MM/yyyy");
                    }
                    else
                    {
                        DateTime thisDate1 = DateTime.Now;
                        txtDateReviewed.Text = thisDate1.ToString("dd/MM/yyyy");

                    }
                }

                TextBox txtResponseOn = (e.Row.FindControl("txtResponseOn") as TextBox);
                if (txtResponseOn != null)
                {

                    var label = (e.Row.FindControl("lblResponseOn") as Label);
                    if (label != null && label.Text.Length >= 1)
                    {
                        txtResponseOn.Text = Convert.ToDateTime(label.Text).ToString("dd/MM/yyyy");
                    }
                    else
                    {
                        DateTime thisDate1 = DateTime.Now;
                        txtResponseOn.Text = thisDate1.ToString("dd/MM/yyyy");

                    }
                }

                TextBox txtAssessmentDate = (e.Row.FindControl("txtAssessmentDate") as TextBox);
                if (txtResponseOn != null)
                {

                    var label = (e.Row.FindControl("lblAssessmentDate") as Label);
                    if (label != null && label.Text.Length >= 1)
                    {
                        txtAssessmentDate.Text = Convert.ToDateTime(label.Text).ToString("dd/MM/yyyy");
                    }
                }

                TextBox txtReportSent = (e.Row.FindControl("txtReportSent") as TextBox);
                if (txtResponseOn != null)
                {

                    var label = (e.Row.FindControl("lblReportSent") as Label);
                    if (label != null && label.Text.Length >= 1)
                    {
                        txtReportSent.Text = Convert.ToDateTime(label.Text).ToString("dd/MM/yyyy");
                    }
                }

                RadioButtonList rblDiscussNextWeek = (e.Row.FindControl("rblDiscussNextWeek") as RadioButtonList);
                if (rblDiscussNextWeek != null)
                {
                    var label = (e.Row.FindControl("lblDiscussNextWeek") as Label);
                    if (label != null && label.Text.Length >= 1)
                    {
                        if (label.Text == "True")
                        {
                            rblDiscussNextWeek.SelectedIndex = 0;
                        }
                        else if(label.Text == "False")
                        {
                           rblDiscussNextWeek.SelectedIndex = 1; 
                        }
                    }
                }

            }

        }

        protected void grdDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdDetails.PageIndex = e.NewPageIndex;
            DataView dvNewAdmitRefs = Getdata();
            grdDetails.DataSource = dvNewAdmitRefs;
            grdDetails.DataBind();
        }

        private DataSet GetData(string query)
        {
            SqlCommand cmd = new SqlCommand(query);
            using (SqlConnection conn = new SqlConnection(Connection.GetConnStrSql()))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = conn;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        return ds;
                    }
                }
            }
        }

        protected DataView Getdata()
        {
            using (SqlConnection conn = new SqlConnection(Connection.GetConnStrSql()))
            {
                DataSet dsContactDetails = new DataSet();
                const string strSelectCmd = StrClient;
                SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
                da.Fill(dsContactDetails, "Contacts");
                DataView dvEmp = dsContactDetails.Tables["Contacts"].DefaultView;
                dvEmp.Sort = ViewState["SortExpr"].ToString();
                return dvEmp;
            }
        }

        protected void grdDetails_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "UpdateAndClose")
            {
                // Retrieve the row index stored in the 
                // CommandArgument property.
                int index = Convert.ToInt32(e.CommandArgument);

                // Retrieve the row that contains the button 
                // from the Rows collection.
                GridViewRow row = grdDetails.Rows[index];

                // Add code here to update
            }

        }
    }
}
